home *** CD-ROM | disk | FTP | other *** search
/ PC Plus SuperCD (UK) 1998 August / PC Plus SuperCD 50b Issue 142 (CD142b) (August 1998).iso / essent / FIXES / CSeries.exe / issue100 / CPROG14.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1994-10-31  |  1.8 KB  |  61 lines

  1. /* CPROG14.CPP - Creating storage space on the fly with the keyword 'new' */
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <conio.h>
  6. #include <stdlib.h>
  7.  
  8. int main(void)
  9. {
  10. struct msgbox { int x, y;        // Structure tag msgbox now defines the template for this type of structure
  11.         char text[100];
  12.         } *fred;        /* *fred is just a pointer, not a
  13.                     structure. Before we can do anything
  14.                     through fred it must be initialised
  15.                     with the address of a msgbox
  16.                     structure. None yet exist. */
  17.  
  18.  
  19.  
  20.     fred=new msgbox;        /* Hopefully, new has found enough
  21.                     free memory for a new msgbox type
  22.                     structure, the address of which
  23.                     goes into fred. */
  24.  
  25.  
  26.     if( fred == NULL )        // Just in case we're tight on RAM...
  27.         {
  28.         cputs("No room for a new test structure");
  29.         exit(0); // 0 goes into ERRORLEVEL to indicate failure
  30.         }
  31.  
  32.     printf("%d\n", sizeof(*fred) );
  33.                     /* Sizeof is a C++ keyword. It tells
  34.                     you the size of the object named in
  35.                     brackets. You can use variable names
  36.                     or data types, such as sizeof(int).
  37.                     With two integers and 100 bytes in a
  38.                     char array, you'd expect the result
  39.                     to be 104. */
  40.  
  41.     // Let's initialise the new structure
  42.     fred->x=30;    // the -> (points to) operator is used when fred is a pointer name instead of a structure name. The expected *fred.x means something different
  43.     fred->y=40;
  44.     strcpy(fred->text, "Greetings from the structure pointed to by fred!\n");
  45.  
  46.     printf("fred->x=%d  fred->y=%d\nfred->text=%s", fred->x, fred->y, fred->text);
  47.     exit(-1);    // Let's push the boat out and have a success code too!
  48. }
  49.  
  50. /* Notes:
  51. 1: A neater way of initialising fred and testing whether the operation
  52. went Ok is:
  53.  
  54.     if( (fred=new msgbox) == NULL )
  55.         printf("Sorry, but we're fresh out of RAM bud.\n");
  56.  
  57. or:
  58.  
  59.     if( ! (fred=new msgbox) )
  60. */
  61.